package com.jzo2o.customer.controller.address;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author itcast
 */
@RestController("AddressController")
@RequestMapping("/consumer/address-book")
@Api(tags = "地址相关接口")
public class AddressController {

    @Autowired
    private IAddressBookService addressBookService;

    /**
     * 新增地址簿接口
     * @param addressBookUpsertReq
     * @return
     */
    @PostMapping
    @ApiOperation("新增地址簿接口")
    public void add(@RequestBody AddressBookUpsertReqDTO addressBookUpsertReq) {
        addressBookService.add(addressBookUpsertReq);
    }

    /**
     * 地址簿分页查询接口
     * @param
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("地址簿分页查询接口")
    public PageResult<AddressBook> selectPage(AddressBookPageQueryReqDTO addressBookPageQueryReq) {
        return addressBookService.pageQury(addressBookPageQueryReq);
    }

    /**
     * 地址簿详情接口
     * @param
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("地址簿详情接口")
    public AddressBook selectPage(@PathVariable("id") Long id) {
        return addressBookService.getById(id);
    }

    /**
     * 地址簿修改
     * @param addressBookUpsertReq
     * @return
     */
    @PutMapping("/{id}")
    @ApiOperation("地址簿修改")
    public void update(@RequestBody AddressBookUpsertReqDTO addressBookUpsertReq,@PathVariable("id") Long id) {
        AddressBook addressBook = new AddressBook();
        BeanUtil.copyProperties(addressBookUpsertReq,addressBook);
        addressBook.setId(id);
        addressBookService.updateById(addressBook);
    }

    /**
     * 地址簿批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/batch")
    @ApiOperation("地址簿批量删除")
    public void update( @RequestBody List<Long> ids) {
        addressBookService.removeByIds(ids);
    }

    /**
     * 设置/取消默认地址
     * @param flag, id
     * @return
     */
    @PutMapping("/default")
    @ApiOperation("设置/取消默认地址")
    public void update(Integer flag,Long id) {
        addressBookService.update(Wrappers.<AddressBook>lambdaUpdate().eq(AddressBook::getId, id).set(AddressBook::getIsDefault,flag));
    }

    /**
     * 获取默认地址
     *
     * @return
     */
    @GetMapping("/defaultAddress")
    @ApiOperation("获取默认地址")
    public AddressBook getDefault() {
        return addressBookService.getOne(Wrappers.<AddressBook>lambdaUpdate().eq(AddressBook::getIsDefault,1).eq(AddressBook::getIsDeleted,0), true);
    }
}
